<?php
namespace app\common\service\swooleJobs;

use app\common\library\CommonFun;
use app\common\model\coin\CoinRuntimeModel;
use app\common\model\ExchangeModel;
use app\common\model\wechat\WeChatExchangeModel;
use app\common\model\wechat\WeChatHistoryModel;
use app\common\model\wechat\WeChatMiniFormIdModel;
use app\common\model\wechat\WeChatMiniPushArticleModel;
use app\common\model\wechat\WeChatPushArticleModel;
use app\common\model\wechat\WeChatUserCoinModel;
use app\common\model\wechat\WeChatUserModel;
use app\common\redis\WeChatPushArticleRepeatRedis;
use app\common\service\ElkLog;
use app\common\service\SwooleJob;
use app\common\service\wechat\WeChatMiniTemplateMsg;
use app\common\service\wechat\WeChatTemplateMsg;

/**
 * Created by PhpStorm.
 * User: 张辉
 * Date: 2018/11/7
 * Time: 15:49
 */

class WeChatPushJobs
{
    /**
     * 加入推送队列
     * @param $open_id
     * @param $coin_id
     */
    public static function firstFollowCoinPushArticlePush( $open_id, $coin_id )
    {
        SwooleJob::push( 'MyJob',__CLASS__ ,'firstFollowCoinPushArticle', array( $open_id, $coin_id ) );
    }

    /**
     * 加入推送队列
     * @param $open_id
     * @param $exchange_id
     */
    public static function firstFollowExchangePushArticlePush( $open_id, $exchange_id )
    {
        SwooleJob::push( 'MyJob',__CLASS__ ,'firstFollowExchangePushArticle', array( $open_id, $exchange_id ) );
    }

    /**
     * 加入推送队列
     * @param $id
     */
    public static function ArticlePushJobs( $id )
    {
        SwooleJob::push( 'MyJob',__CLASS__ ,'pushArticle', array( $id ) );
    }

    /**
     * 加入推送小程序队列
     * @param $id
     */
    public static function MiniArticlePushJobs( $id )
    {
        SwooleJob::push( 'MyJob',__CLASS__ ,'pushWeChatMiniArticle', array( $id ) );
    }

    /**
     * 服务号价格异动推送
     * @param $param
     */
    public static function pushCoinChangePushJobs( $param )
    {
        SwooleJob::push( 'PythonClient',__CLASS__ ,'pushCoinChangePush', array( $param ) );
    }

    /**
     * 服务号价格异动推送方法
     * @param $body
     * @return bool
     */
    public function pushCoinChangePush( $body )
    {
        ElkLog::write( array( "message" => "pushCoinChange", "body" => $body ) );
        if ( time() - $body['time'] > 30 ){
            ElkLog::write( array( "message" => "pushCoinChangeTime", "body" => $body ) );
            return false;
        }

        $WeChatUserCoinModel = new WeChatUserCoinModel();
        $userOpenIdList = $WeChatUserCoinModel->getCoinPushRemindWechatUserOpenIdList( $body['coin_id'] );
        $CoinModel = new CoinRuntimeModel();
        if ( !$body['coin_id'] ){
            return false;
        }

        $coin_info = $CoinModel->get_data_by_id( $body['coin_id']);
        if ( !$coin_info ){
            return false;
        }

        $url = config('coin_token_h5_url').$body['coin_id'];
        $wxTemplateMsgService = new WeChatTemplateMsg();
        CommonFun::get_other_config( 'WxConfig', 2 );
        $wx_config = config( 'HoldAppWeChat' );
        foreach ( $userOpenIdList as $value ){
            ElkLog::write( array( "message" => "pushCoinBody", "body" => $body , "openid" => $value ) );
            $wxTemplateMsgService->sendTempCoinChangeMsg($value, $url, $coin_info['symbol'], $body, $wx_config['WarningTemplateID'] );
        }

        return true;
    }

    /**
     * 微信第一次关注币种推送文章
     * @param $open_id
     * @param $coin_id
     */
    public function firstFollowCoinPushArticle( $open_id, $coin_id )
    {
        ElkLog::write( array( 'message'=> 'firstFollowCoinPushArticle', 'data'=> array( 'open_id'=> $open_id, 'coin_id' => $coin_id ) ) );
        $historyModel = WeChatHistoryModel::getInstance ();
        $WeChatPushArticleModel = WeChatPushArticleModel::getInstance();
        $article = $WeChatPushArticleModel->where( array( 'coin_id'=> $coin_id ) )->order( 'id desc' )->find();
        // 若有文章
        if ( $article ){
            $article = $WeChatPushArticleModel->fill_push( $article );
            // 发送模板消息
            $wxTemplateMsgService = new WeChatTemplateMsg();
            $project  = "\r\n点击查看全文 ↓";
            $wxTemplateMsgService->sendTemplateMsg($open_id, $article['url'], $article['title'], $article['symbol'], $article['remark'], $project);
            //添加历史记录
            $historyModel->addHistory( $open_id, $article['symbol'], $article['title'] );
        }
    }


    /**
     * 分批推送微信文章
     * @param $id
     * @return bool
     */
    public function pushArticle( $id )
    {
        ElkLog::write( array( 'message'=> 'WeChatPushJobs_ArticlePush', 'data'=> array( 'id'=> $id ) ) );
        // 公众号文章推送表
        $WeChatPushArticleModel = new WeChatPushArticleModel();
        $WeChatUserCoinModel = new WeChatUserCoinModel();
        $WeChatUserModel     = new WeChatUserModel();
        $redisModel = WeChatPushArticleRepeatRedis::getInstance();

        //用户关注交易所 18.11.13 @thinkphper
        $exmodel       =  new WeChatExchangeModel();
        $model         =  new ExchangeModel();
        // 获取推送信息
        $data = $WeChatPushArticleModel->get_data_by_id( $id );
        $data = $WeChatPushArticleModel->fill_push( $data );
        if ( !$data  || $data['is_push'] != -1 || strtotime( $data['push_time'] ) > time()  ){
            return false;
        }
        if ($data['coin_id'] ==-2) {
            $userOpenIdList = $exmodel->getExchangePushList($data['exchange_id']);
        } elseif($data['coin_id'] >0){
            $userOpenIdList = $WeChatUserCoinModel->getCoinPushWechatUserOpenIdList($data['coin_id']);
        } elseif($data['coin_id'] ==-1){
            $followids = $WeChatUserCoinModel->getFollowOpenids();
            $ids       = $WeChatUserModel->getWechatUids();
            $userOpenIdList = array_values(array_diff($ids, $followids));
        } else {
            $userOpenIdList = $WeChatUserCoinModel->getAllPushWechatUserOpenIdList( );
        }

        $pushList = array();
        if ( $userOpenIdList ) {
            foreach ( $userOpenIdList as $openid ) {
                // 增加文章推送缓存
                if ( !$redisModel->Setnx( 1,$redisModel->getRedisKey( $openid, $data['article_id']) ) ){
                    // 检测3分钟内有推送
                    continue;
                }

                $redisModel->Expire( 180,$redisModel->getRedisKey( $openid, $data['article_id'] ) );
                $data['open_id'] = $openid;
                $pushList[] = $data;
            }
        }

        // 更新状态为已推送
        $update = array(
            'is_push' => 1,
        );

        $WeChatPushArticleModel->update_data($data['id'], $update);

        // 执行代码
        $wxTemplateMsgService = new WeChatTemplateMsg();

        foreach ( $pushList as $value ){
            try {
                if ($value['coin_id'] ==-1) {
                    $project  = "\r\nHOLD的核心服务是基于用户关注的币种，为您推送币种资讯提醒和价格异动提醒。回复币种名称（如 BTC），您会第一时间收到提醒";
                }elseif($value['coin_id'] ==-2){
                    $list = $model->where(['id'=>$value['exchange_id']])->find();
                    $value['symbol'] = $list['name']."交易所";
                    $project  = "\r\n点击查看全文 ↓";
                }else{
                    $project  = "\r\n点击查看全文 ↓";
                }
                $wxTemplateMsgService->sendTemplateMsg($value['open_id'], $value['url'], $value['title'], $value['symbol'], $value['remark'], $project);
            }catch (\Exception $e) {
                echo $e->getCode().PHP_EOL;
                echo $e->getMessage().PHP_EOL;
            }
        }

        return true;
    }

    /**
     * 微信第一次关注交易所推送文章
     * @param $open_id
     * @param $exchange_id
     */
    public function firstFollowExchangePushArticle( $open_id, $exchange_id )
    {
        ElkLog::write( array( 'message'=> 'firstFollowExchangePushArticle', 'data'=> array( 'open_id'=> $open_id, 'exchange_id' => $exchange_id ) ) );
        $historyModel = WeChatHistoryModel::getInstance ();
        $WeChatPushArticleModel = WeChatPushArticleModel::getInstance();
        $model   = ExchangeModel::getInstance();
        $article = $WeChatPushArticleModel->where( array( 'exchange_id'=> $exchange_id, 'coin_id'=>'-2' ) )->order( 'id desc' )->find();
        $list  =  $model->where(['id'=>$exchange_id])->find();
        // 若有文章
        if ( $article ){
            $article = $WeChatPushArticleModel->fill_push( $article );
            // 发送模板消息
            $wxTemplateMsgService = new WeChatTemplateMsg();
            $symbol = $list['name'].'交易所';
            $project  = "\r\n点击查看全文 ↓";
            $wxTemplateMsgService->sendTemplateMsg($open_id, $article['url'], $article['title'], $symbol, $article['remark'], $project);
            //添加历史记录
            $historyModel->addHistory( $open_id, $article['symbol'], $article['title'] );
        }
    }

    /**
     * 推送小程序
     * @param $id
     * @return bool
     */
    public function pushWeChatMiniArticle( $id )
    {
        ElkLog::write( array( 'message'=> 'WeChatMiniPushJobs_ArticlePush', 'data'=> array( 'id'=> $id ) ) );

        $WeChatMiniFormIdModel = WeChatMiniFormIdModel::getInstance();

        $WeChatMiniPushArticleModel = WeChatMiniPushArticleModel::getInstance();

        $data = $WeChatMiniPushArticleModel->get_data_by_id( $id );

        if ( !$data ||  $data['is_push'] != -1 || strtotime( $data['push_time'] ) > time() ){
            return false;
        }

        $data = $WeChatMiniPushArticleModel->fill_push( $data );

        // 获取所有推送的form_id
        $form_list = $WeChatMiniFormIdModel->get_all_form_id();

        // 更新状态为已推送
        $update = array(
            'is_push' => 1,
        );

        $WeChatMiniPushArticleModel->update_data( $id, $update );

        $WeChatMiniTemplateMsg = new WeChatMiniTemplateMsg( "HoldWeMini" );

        // 推送用户
        foreach ( $form_list as $value ){
            $WeChatMiniTemplateMsg->sendTemplateMsg( $value['open_id'], $value['form_id'], $data['url'] ,$data['title'], $data['create_time'] );
            // 删除当前form_id
            $WeChatMiniFormIdModel->delete_data_by_id( $value['id'] );
        }

        return true;
    }

}
